import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {WebSocket} from "../../../common/model/web-socket";

@Component({
  selector: 'site',
  templateUrl: 'site.html'
})
export class SitePage {
  map:any;
  address:string;
  addressList:object[] = [];
  placeSearch:any;
  autocomplete:any;

  constructor(public navCtrl: NavController,public webSocket: WebSocket) {
    this.initMap();
  }

  initMap() {
    let that = this;
    setTimeout(function () {
      //初始化地图
      that.map = new AMap.Map('container', {
        resizeEnable: true
      });
    }, 1000);

    that.autocomplete = new AMap.Autocomplete({
      city: ""
    });

    that.placeSearch = new AMap.PlaceSearch({
      map: that.map
    });  //构造地点查询类

    this.webSocket.connect(1);
  }


  select(e) {
    let that = this;
    that.addressList = [];
    that.map.clearMap();
    // placeSearch.setCity(e.poi.adcode);
    new AMap.Marker({
      position: new AMap.LngLat(e.location.lng,e.location.lat),//poi.location.lng+','+poi.location.lat,
      title: e.name,
      map:that.map
    });
    that.map.setFitView();
    // this.placeSearch.search(e.name,function (status, result) {
    //   that.map.clearMap();
    //   if (status == 'complete' && result.info == 'OK') {
    //     for (let poi of result.poiList.pois) {
    //       let marker =  new AMap.Marker({
    //         position: new AMap.LngLat(poi.location.lng,poi.location.lat),//poi.location.lng+','+poi.location.lat,
    //         title: poi.name,
    //         map:that.map
    //       });
    //     }
    //     that.map.setFitView();
    //   }
    // });  //关键字查询查询
  }

  addressChange(){
    let that = this;
    setTimeout(function () {
      that.autocomplete.search(that.address, function (status, result) {
        if (status == 'complete' && result.info == 'OK') {
          that.addressList = result.tips;
        }else {
          that.addressList = [];
        }
      });
    }, 1000);
  }

  geocoder() {
    let geocoder = new AMap.Geocoder({
      city: "010", //城市，默认：“全国”
      radius: 1000 //范围，默认：500
    });
    let that = this;
    //地理编码,返回地理编码结果
    geocoder.getLocation(this.address, function(status, result) {
      if (status === 'complete' && result.info === 'OK') {
        that.geocoder_CallBack(result);
      }
    });

  }

  //地理编码返回结果展示
  geocoder_CallBack(data) {
    //地理编码结果数组
    let geocode = data.geocodes;
    for (var i = 0; i < geocode.length; i++) {
      this.addMarker(i, geocode[i]);
    }
     this.map.setFitView();
  }

  addMarker(i,d){
    let marker = new AMap.Marker({
      map: this.map,
      position: [ d.location.getLng(),  d.location.getLat()]
    });
    var infoWindow = new AMap.InfoWindow({
      content: d.formattedAddress,
      offset: {x: 0, y: -30}
    });
    marker.on("mouseover", function(e) {
      infoWindow.open(this.map, marker.getPosition());
    });
  }

}
